﻿let newVue = {
  viewer: null,
  tangent: {},
};
// newVue.viewer = this
let modelContainer = {}; // 模型容器
let otherModelAttr = {}; // 模型用到的属性
let lineContainer = {};  // 链路容器
let tangent = {};        // 切线容器
let lineImg = {};        // 链路图片容器
let satelliteLineContainer = []; // 轨迹容器
let interactionLine = {};        // 链路静态动态
let lineColor = {};              // 链路颜色
/**
 *  addModel 添加模型
 * @param {} modelId     模型ID
 * @param {} modelName   模型名称
 * @param {} modelSrc    模型路径
 * @param {} lon         模型经度
 * @param {} lat         模型纬度
 * @param {} height      模型高度
 * @param {} rollP       模型滚动角  40
 * @param {} pitchP      模型俯仰角  60
 * @param {} headingP    模型偏航角  90
 * @param {} modelShow   模型显隐
 * @param {} description 描述信息
 */
// 添加模型
let addModel = (lon, lat, height, headingP, pitchP, rollP, modelId, scale, labelText, modelSrc, url, minMum) => {
  let position = newVue.viewer.Cesium.Cartesian3.fromDegrees(lon, lat, height);
  let roll = newVue.viewer.Cesium.Math.toRadians(rollP);
  let pitch = newVue.viewer.Cesium.Math.toRadians(pitchP);
  let heading = newVue.viewer.Cesium.Math.toRadians(headingP);
  // console.log(heading, pitch, roll);
  // 321
  let hpr = new newVue.viewer.Cesium.HeadingPitchRoll(heading, pitch, roll);
  let orientation = newVue.viewer.Cesium.Transforms.headingPitchRollQuaternion(position, hpr);
  modelContainer[modelId] = {
    position: position,
    orientation: orientation
  };
  newVue.viewer.Cesium.Material.PolylineTrailLinkImage = url;
  let entity = newVue.viewer.viewer.entities.add({
    id: modelId,
    show: true,
    position: new newVue.viewer.Cesium.CallbackProperty(function () {
      return modelContainer[modelId].position;
    }, false),
    orientation: new newVue.viewer.Cesium.CallbackProperty(function () {
      return modelContainer[modelId].orientation;
    }, false),
    // availability: new Cesium.TimeIntervalCollection([new Cesium.TimeInterval({
    //   start: this.startTime,
    //   stop: this.endTime
    // })]),
    model: {
      uri: modelSrc,
      scale: 100,
      minimumPixelSize: minMum,
    },
    billboard: {
      image: newVue.viewer.Cesium.Material.PolylineTrailLinkImage
    },
    /*point: {
      pixelSize: 10,
      color: newVue.viewer.Cesium.Color.fromAlpha(newVue.viewer.Cesium.Color.fromCssColorString("#3DF4F6"), .5),
    },*/
    label: {
      text: labelText,
      font: "13pt Source Han Sans CN",
      fillColor: newVue.viewer.Cesium.Color.fromAlpha(newVue.viewer.Cesium.Color.fromCssColorString("#f6e70b"), 1),
      pixelOffset: new newVue.viewer.Cesium.Cartesian2(25, 25)
    },
  });
  return entity
};

/**
 *  updateModel 更新模型
 * @param {} modelId     模型ID
 * @param {} lon         模型经度
 * @param {} lat         模型纬度
 * @param {} height      模型高度
 * @param {} heading     模型偏航角
 * @param {} pitch       模型俯仰角
 * @param {} roll        模型滚动角
 * @param {} description 描述信息
 */
function updateModel(modelId, lon, lat, height, heading, pitch, roll, description) {
  let position = newVue.viewer.Cesium.Cartesian3.fromDegrees(lon, lat, height);             // 设置位置
  let rollP = newVue.viewer.Cesium.Math.toRadians(roll);                                    // 设置滚动角
  let pitchP = newVue.viewer.Cesium.Math.toRadians(pitch);                                  // 设置俯仰角
  let headingP = newVue.viewer.Cesium.Math.toRadians(heading);                              // 设置偏航角
  let hpr = new newVue.viewer.Cesium.HeadingPitchRoll(headingP, pitchP, rollP);             // 生成四元数
  let orientation = newVue.viewer.Cesium.Transforms.headingPitchRollQuaternion(position, hpr);//设置姿态
  // 更新模型
  modelContainer[modelId] = {
    position: position,
    orientation: orientation
  };
  // console.log(modelContainer[modelId].position);
  /*  let id = newVue.viewer.viewer.entities.getById(modelId);
      id.position = position;
      id.orientation = orientation*/
  // console.log(modelContainer[modelId]);
}

/**
 *  addSmallModel 添加模型
 * modelId     模型ID
 * modelName   模型名称
 * modelSrc    模型路径
 * lon         模型经度
 * lat         模型纬度
 * height      模型高度
 * rollP       模型滚动角
 * pitchP      模型俯仰角
 * headingP    模型偏航角
 */
let addSmallModel = (lon, lat, height, rollP, pitchP, headingP, modelId, modelSrc, scale, animationLoop) => {
  let position = newVue.viewer.Cesium.Cartesian3.fromDegrees(lon, lat, height);
  let pitch = newVue.viewer.Cesium.Math.toRadians(pitchP);
  let quat = newVue.viewer.Cesium.Quaternion.fromAxisAngle(newVue.viewer.Cesium.Cartesian3.UNIT_Y, pitch);
  let mat3 = newVue.viewer.Cesium.Matrix3.fromQuaternion(quat);
  let mat4 = newVue.viewer.Cesium.Matrix4.fromRotationTranslation(mat3, newVue.viewer.Cesium.Cartesian3.ZERO);
  let modelMatrix = newVue.viewer.Cesium.Transforms.eastNorthUpToFixedFrame(position);
  let finalModel = newVue.viewer.Cesium.Matrix4.multiplyTransformation(modelMatrix, mat4, new newVue.viewer.Cesium.Matrix4());
  otherModelAttr[modelId] = {
    finalModel: finalModel,
  };
  modelContainer[modelId] = newVue.viewer.Cesium.Model.fromGltf({
    id: modelId,
    url: modelSrc,
    modelMatrix: otherModelAttr[modelId].finalModel,
    show: true,
    scale: scale,
    minimumPixelSize: 100,
  });
  let primitive = newVue.viewer.viewer.scene.primitives.add(modelContainer[modelId]);
  newVue.viewer.Cesium.when(primitive.readyPromise).then((primitive) => {
    primitive.activeAnimations.addAll({
      speedup: 1,
      loop: animationLoop,
    });
    console.log(primitive);
    // if (nodeName == "diduan_tx") {
    //   let node = primitive.getNode(nodeName);
    //   let nodeQuat = newVue.viewer.Cesium.Quaternion.fromAxisAngle(newVue.viewer.Cesium.Cartesian3.UNIT_Y, newVue.viewer.Cesium.Math.toRadians(0));
    //   let pt = newVue.viewer.Cesium.Quaternion.fromAxisAngle(newVue.viewer.Cesium.Cartesian3.UNIT_Y, newVue.viewer.Cesium.Math.toRadians(90));
    //   let mat3 = newVue.viewer.Cesium.Matrix3.fromQuaternion(nodeQuat);
    //   let mat2 = newVue.viewer.Cesium.Matrix3.fromQuaternion(pt);
    //   node.matrix = newVue.viewer.Cesium.Matrix4.fromRotationTranslation(mat3, mat2, node.matrix);
    //   // nodeShow(primitive, "diduan_tx", 45, newVue.viewer.Cesium.Cartesian3.UNIT_Z)
    // }
    // let node = primitive.getNode("A1-1");
    // console.log(node);
  });


  return primitive
};

// 模型部件姿态调整
let nodeShow = (primitive, nodeName, nodePitch, cesiumUNIT) => {
  let node = primitive.getNode(nodeName);
  if (nodeName == "diduan_tx") {
    let nodeQuat = newVue.viewer.Cesium.Quaternion.fromAxisAngle(cesiumUNIT, newVue.viewer.Cesium.Math.toRadians(nodePitch));
    let mat3 = newVue.viewer.Cesium.Matrix3.fromQuaternion(nodeQuat);
    node.matrix = newVue.viewer.Cesium.Matrix4.fromRotationTranslation(mat3, newVue.viewer.Cartesian3.ZERO, node.matrix)
  }

};

/**
 *  updateSmallModel 更新小窗口模型
 * @param {} modelId     模型ID
 * @param {} lon         模型经度
 * @param {} lat         模型纬度
 * @param {} height      模型高度
 * @param {} heading     模型偏航角
 * @param {} pitch       模型俯仰角
 * @param {} roll        模型滚动角
 * @param {} description 描述信息
 */
function updateSmallModel(modelId, lon, lat, height, heading, pitchP, roll, description) {
  let position = newVue.viewer.Cesium.Cartesian3.fromDegrees(lon, lat, height); //设置位置
  let pitch = newVue.viewer.Cesium.Math.toRadians(pitchP);
  let quat = newVue.viewer.Cesium.Quaternion.fromAxisAngle(newVue.viewer.Cesium.Cartesian3.UNIT_Y, pitch);
  let mat3 = newVue.viewer.Cesium.Matrix3.fromQuaternion(quat);
  let mat4 = newVue.viewer.Cesium.Matrix4.fromRotationTranslation(mat3, newVue.viewer.Cesium.Cartesian3.ZERO);
  let modelMatrix = newVue.viewer.Cesium.Transforms.eastNorthUpToFixedFrame(position);
  let finalModel = newVue.viewer.Cesium.Matrix4.multiplyTransformation(modelMatrix, mat4, new newVue.viewer.Cesium.Matrix4());
  // 更新模型
  modelContainer[modelId].modelMatrix = finalModel
  /*  id.position = position;
    id.orientation = orientation*/
}

/**
 *  添加链路
 *  @param  data: [90,0,2500000,140,0,2500000]   两个实体间的经纬度高度数据
 *  @param  wid: 宽度
 *  */
function addLink(id, data, wid, opacity, linkColor, imgUrl, time, interactionState) {

  function PolylineTrailLinkMaterialProperty(color, duration) {
    this._definitionChanged = new newVue.viewer.Cesium.Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this.color = color;
    this.duration = duration;
    this._time = (new Date()).getTime();
  }

  newVue.viewer.Cesium.defineProperties(PolylineTrailLinkMaterialProperty.prototype, {
    isConstant: {
      get: function () {
        return false;
      }
    },
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      }
    },
    color: newVue.viewer.Cesium.createPropertyDescriptor("color")
  });
  PolylineTrailLinkMaterialProperty.prototype.getType = function (time) {
    return "PolylineTrailLink";
  };
  // 链路容器
  lineImg[id] = imgUrl;
  PolylineTrailLinkMaterialProperty.prototype.getValue = function (time, result) {
    if (!newVue.viewer.Cesium.defined(result)) {
      result = {};
    }
    result.color = newVue.viewer.Cesium.Property.getValueOrClonedDefault(
      this._color,
      time,
      newVue.viewer.Cesium.Color.WHITE,
      result.color
    );
    result.image = lineImg[id];
    // result.image = "";
    interactionLine[id] = interactionState;
    /**
     * 传输状态
     * 0 未传输
     * 1 开始传输
     * */
    if (interactionLine[id] === 0) {
      result.time = "";
    } else {
      result.time = ((new Date().getTime() - this._time) % this.duration) / this.duration;
    }
    return result;
  };
  PolylineTrailLinkMaterialProperty.prototype.equals = function (other) {
    return this === other || (other instanceof PolylineTrailLinkMaterialProperty && Property.equals(this._color, other._color))
  };
  newVue.viewer.Cesium.PolylineTrailLinkMaterialProperty = PolylineTrailLinkMaterialProperty;
  newVue.viewer.Cesium.Material.PolylineTrailLinkType = "PolylineTrailLink";
  // newVue.viewer.Cesium.Material.PolylineTrailLinkImage = "/static/model/images/dataTransmission.png";
  newVue.viewer.Cesium.Material.PolylineTrailLinkImage = "";
  newVue.viewer.Cesium.Material.PolylineTrailLinkSource = `czm_material czm_getMaterial(czm_materialInput materialInput){
                                                            czm_material material = czm_getDefaultMaterial(materialInput);
                                                            vec2 st = materialInput.st;
                                                            vec4 colorImage = texture2D(image, vec2(fract(st.s - time), st.t));
                                                            material.alpha = colorImage.a * color.a;
                                                            material.diffuse = (colorImage.rgb+color.rgb)/5.0;
                                                            return material;
                                                          }`;
  newVue.viewer.Cesium.Material._materialCache.addMaterial(newVue.viewer.Cesium.Material.PolylineTrailLinkType, {
    fabric: {
      type: newVue.viewer.Cesium.Material.PolylineTrailLinkType,
      uniforms: {
        image: newVue.viewer.Cesium.Material.PolylineTrailLinkImage,
        color: new newVue.viewer.Cesium.Color(1.0, 0.0, 0.0, 0.5),
        time: 0
      },
      source: newVue.viewer.Cesium.Material.PolylineTrailLinkSource
    },
    translucent: function (material) {
      return true;
    }
  });

  lineContainer[id] = data;
  lineColor[id] = linkColor;
  let line = newVue.viewer.viewer.entities.add({
    id,
    polyline: {
      positions: new newVue.viewer.Cesium.CallbackProperty(function () {
        return newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(lineContainer[id]);
      }, false),
      width: wid,
      // clampToGround: true,   // 贴地
      material: new newVue.viewer.Cesium.PolylineTrailLinkMaterialProperty(newVue.viewer.Cesium.Color.fromCssColorString(lineColor[id]), time),
      arcType: newVue.viewer.Cesium.ArcType.NONE,
    }
  });
  return line;
}

/*function parabolaEquation(options, num, height, resultOut) {
  //方程 y=-(4h/L^2)*x^2+h h:顶点高度 L：横纵间距较大者
  var h = height && height > 5000 ? 0 : 0;
  var L = Math.abs(options[0] - options[3]) > Math.abs(options[1] - options[4]) ? Math.abs(options[0] - options[3]) : Math.abs(options[1] - options[4]);
  var num = num && num > 50 ? num : 50;
  var result = [];
  var dlt = L / num;
  if (Math.abs(options[0] - options[3]) > Math.abs(options[1] - options[4])) {//以lon为基准
    var delLat = (options[4] - options[1]) / num;
    if (options[0] - options[3] > 0) {
      dlt = -dlt;
    }
    for (var i = 0; i < num; i++) {
      var tempH = h - Math.pow((-0.5 * L + Math.abs(dlt) * i), 2) * 4 * h / Math.pow(L, 2);
      var lon = options[0] + dlt * i;
      var lat = options[1] + delLat * i;
      result.push([lon, lat, tempH]);
    }
  } else {//以lat为基准
    var delLon = (options[3] - options[0]) / num;
    if (options[1] - options[4] > 0) {
      dlt = -dlt;
    }
    for (var i = 0; i < num; i++) {
      var tempH = h - Math.pow((-0.5 * L + Math.abs(dlt) * i), 2) * 4 * h / Math.pow(L, 2);
      var lon = options[0] + delLon * i;
      var lat = options[1] + dlt * i;
      result.push([lon, lat, tempH]);
    }
  }
  if (resultOut != undefined) {
    resultOut = result;
  }
  return result;
}



function addLink(id, data, wid, opacity, linkColor, imgUrl, time, interactionState) {
  function PolylineTrailLinkMaterialProperty(color, duration) {
    this._definitionChanged = new newVue.viewer.Cesium.Event();
    this._color = undefined;
    this._colorSubscription = undefined;
    this.color = color;
    this.duration = duration;
    this._time = (new Date()).getTime();
  }

  newVue.viewer.Cesium.defineProperties(PolylineTrailLinkMaterialProperty.prototype, {
    isConstant: {
      get: function () {
        return false;
      }
    },
    definitionChanged: {
      get: function () {
        return this._definitionChanged;
      }
    },
    color: newVue.viewer.Cesium.createPropertyDescriptor("color")
  });
  PolylineTrailLinkMaterialProperty.prototype.getType = function (time) {
    return "PolylineTrailLink";
  };
  // 链路容器
  lineImg[id]  = imgUrl;
  PolylineTrailLinkMaterialProperty.prototype.getValue = function (time, result) {
    if (!newVue.viewer.Cesium.defined(result)) {
      result = {};
    }
    result.color = newVue.viewer.Cesium.Property.getValueOrClonedDefault(
      this._color,
      time,
      newVue.viewer.Cesium.Color.WHITE,
      result.color
    );
    result.image = lineImg[id];
    let interactionLine = interactionState;
    /!**
     * 传输状态
     * 0 未传输
     * 1 开始传输
     * *!/
    if (interactionLine) {
      result.time = ((new Date().getTime() - this._time) % this.duration) / this.duration;
    } else {
      result.time = ""
    }
    // result.time = ((new Date().getTime() - this._time) % this.duration) / this.duration;
    return result;
  };
  PolylineTrailLinkMaterialProperty.prototype.equals = function (other) {
    return this === other || (other instanceof PolylineTrailLinkMaterialProperty && Property.equals(this._color, other._color))
  };
  newVue.viewer.Cesium.PolylineTrailLinkMaterialProperty = PolylineTrailLinkMaterialProperty;
  newVue.viewer.Cesium.Material.PolylineTrailLinkType = "PolylineTrailLink";
  newVue.viewer.Cesium.Material.PolylineTrailLinkImage = "/static/model/images/dataTransmission.png";
  newVue.viewer.Cesium.Material.PolylineTrailLinkSource = `czm_material czm_getMaterial(czm_materialInput materialInput){
                                                            czm_material material = czm_getDefaultMaterial(materialInput);
                                                            vec2 st = materialInput.st;
                                                            vec4 colorImage = texture2D(image, vec2(fract(st.s - time), st.t));
                                                            material.alpha = colorImage.a * color.a;
                                                            material.diffuse = (colorImage.rgb+color.rgb)/5.0;
                                                            return material;
                                                          }`;
  newVue.viewer.Cesium.Material._materialCache.addMaterial(newVue.viewer.Cesium.Material.PolylineTrailLinkType, {
    fabric: {
      type: newVue.viewer.Cesium.Material.PolylineTrailLinkType,
      uniforms: {
        image: newVue.viewer.Cesium.Material.PolylineTrailLinkImage,
        color: new newVue.viewer.Cesium.Color(1.0, 0.0, 0.0, 0.5),
        time: 0
      },
      source: newVue.viewer.Cesium.Material.PolylineTrailLinkSource
    },
    translucent: function (material) {
      return true;
    }
  });
  lineContainer[id] = data;
  var points = parabolaEquation(lineContainer[id], 50, 50000)
  var pointArr = [];
  for (var i = 0; i < points.length; i++) {
    pointArr.push(points[i][0], points[i][1],  points[i][2])
  };
  lineContainer[id] = pointArr;
  let line = newVue.viewer.viewer.entities.add({
    id,
    polyline: {
      positions: new newVue.viewer.Cesium.CallbackProperty(function () {
        return newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(lineContainer[id]);
      }, false),
      width: wid,
      material: new newVue.viewer.Cesium.PolylineTrailLinkMaterialProperty(newVue.viewer.Cesium.Color.fromCssColorString(linkColor), time),
      arcType: newVue.viewer.Cesium.ArcType.NONE,
    }
  });
  return line;
}*/

/**
 * 更新链路
 * interactionType：     链路类型 1：类型5 2：类型3 3：类型4
 * state：状态           0：正常 1：断续 2：中断
 * lineContainer[id]     更新位置
 * lineImg[id]           更新正常/断续/中断
 * interactionLine[id]   终端显示静态的0
 * lineColor[id]         更新状态颜色正常：绿色/断续：黄色/中断：红色
 * */
function updateLink(id, data, interactionType, state, color) {
  console.log(id, data, interactionType, state, color);
  lineContainer[id] = data;
  if (interactionType === 1) {
    if (state === 0) {
      lineImg[id] = "../../static/images/1.1.png";
    } else if (state === 1) {
      lineImg[id] = "../../static/images/1.2.png";
    } else {
      lineImg[id] = "";
      interactionLine[id] = 0;
    }
  } else if (interactionType === 2) {
    if (state === 0) {
      lineImg[id] = "../../static/images/1.1.png";
    } else if (state === 1) {
      lineImg[id] = "../../static/images/1.2.png";
    } else {
      lineImg[id] = "";
      interactionLine[id] = 0;
    }
  } else {
    if (state === 0) {
      lineImg[id] = "../../static/images/1.1.png";
    } else if (state === 1) {
      lineImg[id] = "../../static/images/1.2.png";
    } else {
      lineImg[id] = "";
      interactionLine[id] = 0;
    }
  }
  lineColor[id] = color;
  newVue.viewer.viewer.entities.getById(id).polyline.material.color = newVue.viewer.Cesium.Color.fromCssColorString(lineColor[id])
}

/**
 * 移除实体
 * @param {} entitiesId 目标id
 */
function removeControl(entitiesId) {
  newVue.viewer.viewer.entities.remove(newVue.viewer.viewer.entities.getById(entitiesId))   // 移除此元素
}

/**
 * 创建轨迹 createLine("aa","aa",[-75, 39, 250000,-125, 39, 250000],red,0.5)
 * polylineArr 轨迹数据
 * */
// 创建卫星轨迹
let createLine = (id, polylineArr, color, alpha) => {
  satelliteLineContainer[id + "line"] = polylineArr;
  let line = newVue.viewer.viewer.entities.add({
    id: id + "line",
    show: true,
    polyline: {
      positions: newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(satelliteLineContainer[id + "line"]),
      width: 2,
      material: newVue.viewer.Cesium.Color.fromAlpha(newVue.viewer.Cesium.Color.fromCssColorString(color), alpha)
    }
  });
  return line;
};

// 更新卫星轨迹
let updateSocketLine = (id, data) => {
  satelliteLineContainer[id + "line"] = data;
  newVue.viewer.viewer.entities.getById(id + "line").polyline.positions = newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(satelliteLineContainer[id + "line"]);
};
// 存数据 高度为0的轨迹/路径
let createLineHeight0 = (id, polylineArr, color, alph, lineHeightContainer) => {
  lineHeightContainer[id + "line"] = polylineArr;
  let line = newVue.viewer.viewer.entities.add({
    id: id + "line",
    show: true,
    polyline: {
      positions: newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(lineHeightContainer[id + "line"]),
      width: 2,
      material: newVue.viewer.Cesium.Color.fromAlpha(newVue.viewer.Cesium.Color.fromCssColorString(color), alph)
    }
  });
  return line;
};

// 更新数据  高度为0的轨迹/路径
let updateLine = (id, data, lineHeightContainer) => {
  lineHeightContainer[id] = data;
  newVue.viewer.viewer.entities.getById(id).polyline.positions = newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(lineHeightContainer[id]);
};
/*// 存数据 高度为0的轨迹/路径
let createLineHeight0 = (id, polylineArr, color, alph, lineHeightContainer) => {
  lineHeightContainer[id + "line"] = polylineArr;
  let line = newVue.viewer.viewer.entities.add({
    id: id + "line",
    show: true,
    polyline: {
      positions: new newVue.viewer.Cesium.CallbackProperty(function (){
        return newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(lineHeightContainer[id + "line"]);
      }, false),
      width: 2,
      material: newVue.viewer.Cesium.Color.fromAlpha(newVue.viewer.Cesium.Color.fromCssColorString(color), alph)
    }
  });
  return line;
};

// 更新数据  高度为0的轨迹/路径
let updateLine = (id ,data, lineHeightContainer) => {
  lineHeightContainer[id] = data;
};*/

// 创建轨迹
let createPrimitive = (data, color) => {
  let primitive = new newVue.viewer.Cesium.Primitive({
    geometryInstances: new newVue.viewer.Cesium.GeometryInstance({
      geometry: new newVue.viewer.Cesium.PolylineGeometry({
        positions: newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(data),
        width: 2,
        vertexFormat: newVue.viewer.Cesium.PolylineColorAppearance.VERTEX_FORMAT
      }),
      attributes: {
        color: newVue.viewer.Cesium.ColorGeometryInstanceAttribute.fromColor(newVue.viewer.Cesium.Color.fromCssColorString(color))
      },
    }),
    appearance: new newVue.viewer.Cesium.PolylineColorAppearance({
      translucent: true        // 透明
    })
  });
  // console.log(data, primitive);
  newVue.viewer.viewer.scene.primitives.add(primitive);
  return primitive
};

// 创建轨迹
let createBeamPrimitive = (beamID, data, color) => {
  let primitive = new newVue.viewer.Cesium.Primitive({
    geometryInstances: new newVue.viewer.Cesium.GeometryInstance({
      geometry: new newVue.viewer.Cesium.PolylineGeometry({
        positions: newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(data),
        width: 2,
        vertexFormat: newVue.viewer.Cesium.PolylineColorAppearance.VERTEX_FORMAT
      }),
      attributes: {
        color: newVue.viewer.Cesium.ColorGeometryInstanceAttribute.fromColor(newVue.viewer.Cesium.Color.fromCssColorString(color))
      },
      id: beamID
    }),
    appearance: new newVue.viewer.Cesium.PolylineColorAppearance({
      translucent: true        // 透明
    })
  });
  // console.log(data, primitive);
  newVue.viewer.viewer.scene.primitives.add(primitive);
  return primitive
};


/*let moreLine = (id, data) => {
  let polylines = new newVue.viewer.Cesium.PolylineCollection();
  let Color = new newVue.viewer.Cesium.Color(1, 1, 1,0.5);
  let p = polylines.add({
    positions: new newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(data),
    width: 2,
  });
  polylines.id = id;
  p.material = newVue.viewer.Cesium.Material.fromType('Color');
  p.material.uniforms.color = Color;
  newVue.viewer.viewer.scene.primitives.add(polylines);
  return polylines;
};*/

// 创建轨迹方法
// let newLine = (positions) => {
//   let polylines = new newVue.viewer.Cesium.PolylineCollection();
//   polylines.add({
//     positions: positions,
//     width: 2,
//     material: {
//       fabic
//     }
//   })
// };


/* 经纬网格 */
function createGridLine(width) {
  let polylines = new newVue.viewer.Cesium.PolylineCollection();
  let Color = new newVue.viewer.Cesium.Color(1, 1, 1, 0.5);
  let labelScale = 0.8;
  // 画纬度标签
  for (var lat = -90; lat <= 90; lat += width) {
    let line = [];
    for (var lon = -180; lon <= 180; lon += width) {
      line.push(new newVue.viewer.Cesium.Cartesian3.fromDegrees(lon, lat, 100000))
    }
    let p = polylines.add({
      positions: line,
      width: labelScale
    });
    p.material = newVue.viewer.Cesium.Material.fromType('Color');
    p.material.uniforms.color = Color;
  }
  // 画经度度标签
  for (var lon = -180; lon <= 180; lon += width) {
    let line = [];
    for (var lat = -90; lat <= 90; lat += width) {
      line.push(new newVue.viewer.Cesium.Cartesian3.fromDegrees(lon, lat, 100000),)
    }
    let p = polylines.add({
      positions: line,
      width: labelScale
    });
    p.material = newVue.viewer.Cesium.Material.fromType('Color');
    p.material.uniforms.color = Color;
  }
  polylines.id = 'line';
  newVue.viewer.viewer.scene.primitives.add(polylines);
  return polylines;
}

/* 经纬标签 */
function createGridLabel(width) {
  let labels = new newVue.viewer.Cesium.LabelCollection();
  let Color = new newVue.viewer.Cesium.Color(1, 1, 1, 0.5);
  // 画纬度标签
  for (var lat = -90; lat <= 90; lat += width) {
    for (var lon = -180; lon <= 180; lon += width) {
      var label = labels.add({
        position: new newVue.viewer.Cesium.Cartesian3.fromDegrees(lon, lat, 100000),
        text: lon + '°/' + lat + '°',
        scale: 0.4,
        fillColor: Color,
        pixelOffset: new newVue.viewer.Cesium.Cartesian2(10, 10)
      });
    }
  }
  // 画经度度标签
  label.id = 'label';
  newVue.viewer.viewer.scene.primitives.add(labels);
  return labels;
}


// 创建切面
let createBeamLine = (id, polylineArr, color, alpha) => {
  tangent[id] = polylineArr;
  let line = newVue.viewer.viewer.entities.add({
    id: id,
    show: true,
    polyline: {
      positions: newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(tangent[id]),
      width: 2,
      material: newVue.viewer.Cesium.Color.fromAlpha(newVue.viewer.Cesium.Color.fromCssColorString(color), alpha)
    }
  });
  return line;
};

// 更新卫星轨迹
let updateBeamLine = (id, data, color, alpha) => {
  tangent[id] = data;
  newVue.viewer.viewer.entities.getById(id).polyline.positions = newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(tangent[id]);
  newVue.viewer.viewer.entities.getById(id).polyline.meterial = newVue.viewer.Cesium.Color.fromAlpha(newVue.viewer.Cesium.Color.fromCssColorString(color), alpha);
};


/**
 * 卫星波束
 * @param {} canvas     材质 canvas 及 圆半径 ["canvas-a", 5], ["canvas-b", 10], ["canvas-c", 15]
 * @param {} id         编号
 * @param {} name       名称
 * @param {} lon        经度
 * @param {} lat        纬度
 * @param {} height     高度
 * @param boolean  type  true 吐圈圈  false 吞圈圈
 * @param boolean  workState   true 有圈效果  false  无圈效果
 */
/* 创建波束 */
/*let renderSatBeam = (id, stltPos, points, color, type, workState) => {
  // console.log(points.join(","));
  let arr = [stltPos[0], stltPos[1], stltPos[2]];
  let arrZero = [];
  for (let i = 0; i < points.length; i += 3) {
    if (i + 3 == points.length) {
      arr.push(points[0], points[1], points[2])
    } else {
      if (points[i + 2] === -0) {
        arrZero.push(points[i], points[i + 1], points[i + 2])
      };
      arr.push(points[i], points[i + 1], points[i + 2])
    }
  }
  if (arrZero.length === 0) {
    arrZero = [0, 0, 0, 0, 0, 0]
  }
  // console.log(arrZero, "arrZero");
  let myPositions = newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(arr);
  // 构建锥体
  let n = myPositions.length;   // arr,length / 3 = myPositions
  let positions = new Float64Array(3 * n);
  let indices = new Uint16Array(3 * (n - 2));
  let index = 0;
  let indicesIndex = 0;
  for (let i = 0; i < n; ++i) {
    positions[index++] = myPositions[i].x;
    positions[index++] = myPositions[i].y;
    positions[index++] = myPositions[i].z;
    if (i < (n - 2)) {
      indices[indicesIndex++] = 0;
      indices[indicesIndex++] = i + 1;
      indices[indicesIndex++] = i + 2;
    }
  }
  // console.log(arr, "arr");
  let geometry = new  newVue.viewer.Cesium.Geometry({
    attributes: {
      position: new  newVue.viewer.Cesium.GeometryAttribute({
        componentDatatype:  newVue.viewer.Cesium.ComponentDatatype.DOUBLE,
        componentsPerAttribute: 3,
        values: positions
      })
    },
    indices: indices,
    primitiveType:  newVue.viewer.Cesium.PrimitiveType.TRIANGLES,
    boundingSphere:  newVue.viewer.Cesium.BoundingSphere.fromVertices(positions)
  });

  /!**
   * 判断接收数据的workState
   * 0 静态
   * 1 动态
   * *!/
  if (workState === 0) {
    workState = false
  } else if (workState === 1) {
    workState = true
  } else {
    workState = false
  }
  /!**
   * 判断接收数据的type
   * 1 是吞圈
   * 其余的是吐圈
   * 3 类型3
   * 4 遥测
   * 5 遥控
   * 6 类型5
   * *!/
  if (type === 1) {
    type = true;
    color = "rgba(16,255,209,0.2)"
  } else if (type === 2) {
    type = false;
    color = "rgba(10,245,255,0.2)"
  } else if (type === 3) {
    type = false;
    color = "rgba(6,118,255,0.2)"
  } else if (type === 4) {
    type = false;
    color = "rgba(21,75,255,0.2)"
  } else if (type === 5) {
    type = false;
    color = "rgba(0,255,192,0.2)"
  } else if (type === 6) {
    type = false;
    color = "rgba(10,245,255,0.2)"
  } else {
    type = false;
    color = "rgba(35,248,255, 0.2)"
  }

  let instance = new  newVue.viewer.Cesium.GeometryInstance({
    geometry: geometry,
    // modelMatrix : Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
    // Cesium.Cartesian3.fromDegrees(105.59777, 40.03883,30000)), new Cesium.Cartesian3(0.0, 0.0, 0.0), new Cesium.Matrix4()),
    attributes: {
      color:  newVue.viewer.Cesium.ColorGeometryInstanceAttribute.fromColor(newVue.viewer.Cesium.Color.fromCssColorString(color))
    },
    id: "top"
  });
  let geometryZero = new  newVue.viewer.Cesium.PolylineGeometry({
    positions: newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(points),
    width: 20,
    vertexFormat: newVue.viewer.Cesium.PolylineColorAppearance.VERTEX_FORMAT
  });
  let abc = new newVue.viewer.Cesium.GeometryInstance({
    geometry: geometryZero,
    attributes: {
      color: newVue.viewer.Cesium.ColorGeometryInstanceAttribute.fromColor(newVue.viewer.Cesium.Color.fromCssColorString(color))
    },
  });
  // console.log(abc, "abc===");
  let vs = "attribute vec3 position3DHigh;\n\
attribute vec3 position3DLow;\n\
attribute vec4 color;\n\
attribute float batchId;\n\
varying vec4 v_color;\n\
varying vec4 v_localPos;\n\
void main()\n\
{\n\
	v_localPos = vec4(position3DHigh + position3DLow, 1.0);\n\
	vec4 p = czm_computePosition();\n\
	v_color = color;\n\
	gl_Position = czm_modelViewProjectionRelativeToEye * p;\n\
	// v_localPos = (czm_inverseModel * v_localPos);\n\
}";

  let fs = "varying vec4 v_color;\
varying vec4 v_localPos;\
uniform float u_simuTime;\n\
uniform float heights;\n\
void main()\
{\
	float startLength = fract(u_simuTime) * heights;\n\
	float endLength = startLength+5000000.0;\n\
	float halfWidth = (endLength-startLength)/2.0;\n\
	float curLength = length(v_localPos.xyz);\n\
	float centerLength = startLength + halfWidth;\n\
	float maxAlpha = 1.0;\n\
	float minAlpha = 0.2;\n\
	if(curLength > startLength && curLength < endLength)\
	{\n\
		vec3 rgb = vec3(1.0,1.0,0.0);\n\
		float disToCenter = abs(curLength-centerLength);\n\
		float waveAlpha = (minAlpha - maxAlpha) * disToCenter / halfWidth + maxAlpha;\n\
		gl_FragColor = vec4(rgb.xyz,waveAlpha);\n\
	}\n\
	else\n\
	{\n\
		// gl_FragColor = czm_gammaCorrect(v_color);\n\
		gl_FragColor = v_color;\n\
	}\n\
}";
  let appearance = new newVue.viewer.Cesium.PerInstanceColorAppearance({
    flat: true,
    translucent: true,
    vertexShaderSource: vs,
    fragmentShaderSource: fs
  });

  let primitive = new newVue.viewer.Cesium.Primitive({
    // geometryInstances: [instance, abc],
    geometryInstances: [instance],
    appearance: appearance,
    // modelMatrix: Cesium.Matrix4.multiplyByTranslation(Cesium.Transforms.eastNorthUpToFixedFrame(
    // Cesium.Cartesian3.fromDegrees(105.59777, 40.03883, 800000)), new Cesium.Cartesian3(0.0, 0.0, 0.0), new Cesium.Matrix4()),
    asynchronous: false
  });
  let material = {
    isTranslucent: function () {
      return true;
    },
    update: function () {

    }
  };
  let time = 0;
  material._uniforms = {
    u_simuTime: function () {
      if (type) {
        if (time <= 0) {
          time = 0;
          time += 0.003
        } else {
          time += 0.003
        }
      } else {
        if (time <= 0) {
          time = 2;
          time -= 0.003
        } else {
          time -= 0.003
        }
      }
      return time
    },
    heights: function () {
      if (workState) {
        return stltPos[2] * 5
      } else {
        return ""
      }
    }
  };
  // createBeamPrimitive(id, points, color);
  appearance.material = material;
  newVue.viewer.viewer.scene.primitives.add(primitive);
  return primitive
};*/

let renderSatBeam = (id, stltPos, points, shellcolor, type, workState, isShowLine) => {
  let numtriangles = points.length / 3;
  let arr = [stltPos[0], stltPos[1], stltPos[2]];
  let arrZero = [];
  let newArr = [];
  for (let i = 0; i < points.length; i += 3) {
    if (i + 3 === points.length) {
      arr.push(points[0], points[1], points[2]);
      // arrZero.push(arrZero[0], arrZero[1], arrZero[2]);
      // newArr.push(newArr[0], newArr[1], newArr[2]);
    } else {
      // if (points[i + 2] === -0 || points[i + 2] === 0) {
      if (points[i + 2] < 10) {
        arrZero.push(points[i], points[i + 1], points[i + 2]);
      } else {
        newArr.push(points[i], points[i + 1], points[i + 2]);
      }
      arr.push(points[i], points[i + 1], points[i + 2])
    }
  }
  let myPositions = newVue.viewer.Cesium.Cartesian3.fromDegreesArrayHeights(arr);
  let positions = new Float64Array(3 * (numtriangles * 2 + 1));
  let sts = new Float32Array(2 * (numtriangles * 2 + 1));
  let indices = new Uint16Array(3 * numtriangles);

  positions[0] = myPositions[0].x;
  positions[1] = myPositions[0].y;
  positions[2] = myPositions[0].z;
  sts[0] = 0.5;
  sts[1] = 1.0;
  let vertexcount = 2;
  let stcount = 1;
  let indexcount = 0;
  let distance = newVue.viewer.Cesium.Cartesian3.distance(myPositions[1], myPositions[0]);
  let tempdistance = newVue.viewer.Cesium.Cartesian3.distance(myPositions[1], myPositions[0]);
  for (var i = 0; i < myPositions.length - 2; i++) {
    positions[++vertexcount] = myPositions[i + 1].x;
    positions[++vertexcount] = myPositions[i + 1].y;
    positions[++vertexcount] = myPositions[i + 1].z;
    sts[++stcount] = 0.0;
    tempdistance = newVue.viewer.Cesium.Cartesian3.distance(myPositions[i + 1], myPositions[0]);
    sts[++stcount] = 1.0 - tempdistance / distance;
    if (sts[stcount] < 0) sts[stcount] = 0;

    positions[++vertexcount] = myPositions[i + 2].x;
    positions[++vertexcount] = myPositions[i + 2].y;
    positions[++vertexcount] = myPositions[i + 2].z;
    sts[++stcount] = 1.0;
    tempdistance = newVue.viewer.Cesium.Cartesian3.distance(myPositions[i + 2], myPositions[0]);
    sts[++stcount] = 1.0 - tempdistance / distance;
    if (sts[stcount] < 0) sts[stcount] = 0;

    indices[indexcount++] = 0;
    indices[indexcount++] = i * 2 + 1;
    indices[indexcount++] = i * 2 + 2;
  }
  let geometry = new newVue.viewer.Cesium.Geometry({
    attributes: {
      position: new newVue.viewer.Cesium.GeometryAttribute({
        componentDatatype: newVue.viewer.Cesium.ComponentDatatype.DOUBLE,
        componentsPerAttribute: 3,
        values: positions
      }),
      st: new newVue.viewer.Cesium.GeometryAttribute({
        componentDatatype: newVue.viewer.Cesium.ComponentDatatype.FLOAT,
        componentsPerAttribute: 2,
        values: sts
      }),
    },
    indices: indices,
    primitiveType: newVue.viewer.Cesium.PrimitiveType.TRIANGLES,
    boundingSphere: newVue.viewer.Cesium.BoundingSphere.fromVertices(positions)
  });

  /**
   * 判断接收数据的workState
   * 0 静态
   * 1 动态
   * */
  workState = true
  /*if (workState === 0) {
    workState = false
  } else if (workState === 1) {
    workState = true
  } else {
    workState = false
  }*/
  /**
   * 判断接收数据的type
   * 1 是吞圈 侦查
   * 其余的是吐圈 类型2
   * 3 类型3
   * 4 遥测
   * 5 遥控
   * 6 类型5
   * */
  let color = "";
  if (type === "1") {
    type = true;
    color = "rgb(143,98,0,0.47)"
  } else if (type === "2") {
    type = true;
    color = "rgb(0,202,181,0.47)"
  } else if (type === "3") {
    type = true;
    color = "rgb(0,55,202,0.47)"
  } else if (type === "4") {
    type = true;
    color = "rgb(81,0,202,0.47)"
  } else if (type === "5") {
    type = true;
    color = "rgb(0,255,0,0.1)"
  } else if (type === "6") {
    type = true;
    color = "rgb(173,25,255,0.1)"
  } else if (type === "7") {
    type = true;
    color = "rgb(255, 152, 9,0.1)"
  } else {
    type = true;
    color = "rgb(118,25,250,0.1)"
  }

  let instance = new newVue.viewer.Cesium.GeometryInstance({
    geometry: geometry,
    attributes: {
      color: newVue.viewer.Cesium.ColorGeometryInstanceAttribute.fromColor(newVue.viewer.Cesium.Color.fromCssColorString(shellcolor))
    },
  });

  let staticAppearance = new newVue.viewer.Cesium.PerInstanceColorAppearance({
    translucent: true,
  });
  let dynamicAppearance = new newVue.viewer.Cesium.MaterialAppearance({
    material: new newVue.viewer.Cesium.Material({
      fabric: {
        type: "radarS",
        uniforms: {
          color: newVue.viewer.Cesium.Color.fromCssColorString(color),
          shellcolor: newVue.viewer.Cesium.Color.fromCssColorString(shellcolor),
          repeat: 20, // 重复度
          offset: 0,
          speed: (type ? -1 : 1) * 2,
          thickness: 1 // 每个条纹之间的间隔
        },
        source:
          "\n uniform vec4 color;\n" +
          "uniform vec4 shellcolor;\n" +
          "uniform float repeat;\n" +
          "uniform float offset;\n" +
          "uniform float thickness;\n" +
          "uniform float speed;\n" +
          "czm_material czm_getMaterial(czm_materialInput materialInput)\n" +
          "{\n" +
          "czm_material material = czm_getDefaultMaterial(materialInput);\n" +
          "float sp = 1.0/repeat;\n" +
          "vec2 st = materialInput.st;\n" +
          "float dis = 1.0-st.t;\n" +
          "float m = mod(dis + offset-czm_frameNumber*0.001*speed, sp);\n" +
          "float a = step(sp*(1.0-thickness), m);\n" +
          "material.diffuse = a*color.rgb+(1.0-a)*shellcolor.rgb;;\n" +
          "material.alpha = a * color.a+shellcolor.a;\n" +
          "return material;\n" +
          "}\n"
      },
      translucent: true
    }),
    closed: true
  });
  let primitive = new newVue.viewer.Cesium.Primitive({
    geometryInstances: [instance],
    appearance: workState ? dynamicAppearance : staticAppearance,
    asynchronous: false
  });
  isShowLine = [...new Set(isShowLine)];
  // 创建切面
  if (arrZero.length !== 0) {
    arrZero.push(arrZero[0], arrZero[1], arrZero[2]);
    if (workState) {
      /*if (isShowLine.length > 0) {
        for (var i = 0; i < isShowLine.length; i++) {
          if (isShowLine[i].id && isShowLine[i].id === id) {
            if (!isShowLine[i].flag) continue;
            if (tangent[id + "zero"]) {
              tangent[id + "zero"].push(createBeamPrimitive(id, arrZero, color));
              setTimeout(() => {
                let lengthPrimitive = tangent[id + "zero"].length;
                for(let i = 0; i < lengthPrimitive - 1; i++) {
                  newVue.viewer.viewer.scene.primitives.remove(tangent[id + "zero"][i])
                };
                tangent[id + "zero"].splice(0, lengthPrimitive - 1)
              },2000);
            } else {
              tangent[id + "zero"] = [];
              tangent[id + "zero"].push(createBeamPrimitive(id, arrZero, color));
            }
          }
        }
      } else {
        if (tangent[id + "zero"]) {
          tangent[id + "zero"].push(createBeamPrimitive(id, arrZero, color));
          setTimeout(() => {
            let lengthPrimitive = tangent[id + "zero"].length;
            for(let i = 0; i < lengthPrimitive - 1; i++) {
              newVue.viewer.viewer.scene.primitives.remove(tangent[id + "zero"][i])
            };
            tangent[id + "zero"].splice(0, lengthPrimitive - 1)
          },2000);
        } else {
          tangent[id + "zero"] = [];
          tangent[id + "zero"].push(createBeamPrimitive(id, arrZero, color));
        }
      }*/
      if (newVue.viewer.viewer.entities.getById(id + "zero")) {
        updateBeamLine(id + "zero", arrZero, color, 0.5);
      } else {
        createBeamLine(id + "zero", arrZero, color, 0.5);
      }
    } else {
      if (newVue.viewer.viewer.entities.getById(id + "zero")) {
        updateBeamLine(id + "zero", arrZero, shellcolor, 0.5);
      } else {
        createBeamLine(id + "zero", arrZero, shellcolor, 0.5);
      }
      /*if (isShowLine.length > 0) {
        for (var i = 0; i < isShowLine.length; i++) {
          if (isShowLine[i].id && isShowLine[i].id === id) {
            if (!isShowLine[i].flag) continue;
            if (tangent[id + "zero"]) {
              tangent[id + "zero"].push(createBeamPrimitive(id, arrZero, shellcolor));
              setTimeout(() => {
                let lengthPrimitive = tangent[id + "zero"].length;
                for(let i = 0; i < lengthPrimitive - 1; i++) {
                  newVue.viewer.viewer.scene.primitives.remove(tangent[id + "zero"][i])
                };
                tangent[id + "zero"].splice(0, lengthPrimitive - 1)
              },2000);
            } else {
              tangent[id + "zero"] = [];
              tangent[id + "zero"].push(createBeamPrimitive(id, arrZero, shellcolor));
            }
          }
        }
      } else {
        if (tangent[id + "zero"]) {
          tangent[id + "zero"].push(createBeamPrimitive(id, arrZero, shellcolor));
          setTimeout(() => {
            let lengthPrimitive = tangent[id + "zero"].length;
            for(let i = 0; i < lengthPrimitive - 1; i++) {
              newVue.viewer.viewer.scene.primitives.remove(tangent[id + "zero"][i])
            };
            tangent[id + "zero"].splice(0, lengthPrimitive - 1)
          },2000);
        } else {
          tangent[id + "zero"] = [];
          tangent[id + "zero"].push(createBeamPrimitive(id, arrZero, shellcolor));
        }
      }*/
    }
  }

  if (newArr.length !== 0) {
    newArr.push(newArr[0], newArr[1], newArr[2]);
    if (workState) {
      if (newVue.viewer.viewer.entities.getById(id + "bottom")) {
        updateBeamLine(id + "bottom", newArr, color, 0.5);
      } else {
        createBeamLine(id + "bottom", newArr, color, 0.5);
      }

      /*if (isShowLine.length > 0) {
        for (var i = 0; i < isShowLine.length; i++) {
          if (isShowLine[i].id && isShowLine[i].id === id) {
            if (!isShowLine[i].flag) continue;
            if (tangent[id]) {
              tangent[id].push(createBeamPrimitive(id, newArr, color));
              setTimeout(() => {
                let lengthPrimitive = tangent[id].length;
                for(let i = 0; i < lengthPrimitive - 1; i++) {
                  newVue.viewer.viewer.scene.primitives.remove(tangent[id][i])
                };
                tangent[id].splice(0, lengthPrimitive - 1)
              },2000);
            } else {
              tangent[id] = [];
              tangent[id].push(createBeamPrimitive(id, newArr, color));
            }
          }
        }
      } else {
        if (tangent[id]) {
          tangent[id].push(createBeamPrimitive(id, newArr, color));
          setTimeout(() => {
            let lengthPrimitive = tangent[id].length;
            for(let i = 0; i < lengthPrimitive - 1; i++) {
              newVue.viewer.viewer.scene.primitives.remove(tangent[id][i])
            };
            tangent[id].splice(0, lengthPrimitive - 1)
          },2000);
        } else {
          tangent[id] = [];
          tangent[id].push(createBeamPrimitive(id, newArr, color));
        }
      }*/
      /*if (tangent[id]) {
        tangent[id].push(createBeamPrimitive(id, newArr, color));
        setTimeout(() => {
          let lengthPrimitive = tangent[id].length;
          for(let i = 0; i < lengthPrimitive - 1; i++) {
            newVue.viewer.viewer.scene.primitives.remove(tangent[id][i])
          };
          tangent[id].splice(0, lengthPrimitive - 1)
        },2000);
      } else {
        tangent[id] = [];
        tangent[id].push(createBeamPrimitive(id, newArr, color));
      }*/
    } else {

      if (newVue.viewer.viewer.entities.getById(id + "bottom")) {
        updateBeamLine(id + "bottom", newArr, shellcolor, 0.5);
      } else {
        createBeamLine(id + "bottom", newArr, shellcolor, 0.5);
      }

      /*if (isShowLine.length > 0) {
        for (var i = 0; i < isShowLine.length; i++) {
          if (isShowLine[i].id && isShowLine[i].id === id) {
            if (!isShowLine[i].flag) continue;
            if (tangent[id]) {
              tangent[id].push(createBeamPrimitive(id, newArr, shellcolor));
              setTimeout(() => {
                let lengthPrimitive = tangent[id].length;
                for(let i = 0; i < lengthPrimitive - 1; i++) {
                  newVue.viewer.viewer.scene.primitives.remove(tangent[id][i])
                };
                tangent[id].splice(0, lengthPrimitive - 1)
              },2000);
            } else {
              tangent[id] = [];
              tangent[id].push(createBeamPrimitive(id, newArr, shellcolor));
            }
          }
        }
      } else {
        if (tangent[id]) {
          tangent[id].push(createBeamPrimitive(id, newArr, shellcolor));
          setTimeout(() => {
            let lengthPrimitive = tangent[id].length;
            for(let i = 0; i < lengthPrimitive - 1; i++) {
              newVue.viewer.viewer.scene.primitives.remove(tangent[id][i])
            };
            tangent[id].splice(0, lengthPrimitive - 1)
          },2000);
        } else {
          tangent[id] = [];
          tangent[id].push(createBeamPrimitive(id, newArr, shellcolor));
        }
      }*/
      /*if (tangent[id]) {
        tangent[id].push(createBeamPrimitive(id, newArr, shellcolor));
        setTimeout(() => {
          let lengthPrimitive = tangent[id].length;
          for(let i = 0; i < lengthPrimitive - 1; i++) {
            newVue.viewer.viewer.scene.primitives.remove(tangent[id][i])
          };
          tangent[id].splice(0, lengthPrimitive - 1)
        },2000);
      } else {
        tangent[id] = [];
        tangent[id].push(createBeamPrimitive(id, newArr, shellcolor));
      }*/
    }
  }

  newVue.viewer.viewer.scene.primitives.add(primitive);
  return primitive
};
/* 波束更新 */
let updateBeam = (id, primitiveEntity, stltPos, points, shellcolor, type, workState, isShowLine) => {
  let newPrimitiveEntity = "";
  if (primitiveEntity) {
    let saveShowHide = primitiveEntity.show;
    newVue.viewer.viewer.scene.primitives.remove(primitiveEntity);
    // 删除高度为0的切线
    if (newVue.viewer.viewer.entities.getById(id + "zero")) {
      /*var zeroShowHide = newVue.viewer.viewer.entities.getById(id + "zero").show;*/
      removeControl(id + "zero");
    }
    // 删除底部切线
    if (newVue.viewer.viewer.entities.getById(id + "bottom")) {
      /*var bottomShowHide = newVue.viewer.viewer.entities.getById(id + "bottom").show;*/
      removeControl(id + "bottom");
    }
    newPrimitiveEntity = renderSatBeam(id, stltPos, points, shellcolor, type, workState, isShowLine);
    newPrimitiveEntity.show = saveShowHide;
    /*if (newVue.viewer.viewer.entities.getById(id + "bottom")) {
      newVue.viewer.viewer.entities.getById(id + "bottom").show = bottomShowHide;
    }
    if (newVue.viewer.viewer.entities.getById(id + "zero")) {
      newVue.viewer.viewer.entities.getById(id + "zero").show = zeroShowHide;
    }*/
  }
  return newPrimitiveEntity;
};
/* 显示隐藏波束 */
let showIsHideBeam = (primitiveEntity, flag) => {
  if (typeof flag == "boolean") {
    primitiveEntity.show = flag;
  }
};
/* 删除波束 */
let deleteBeam = (primitiveEntity) => {
  newVue.viewer.viewer.scene.primitives.remove(primitiveEntity);
};

// 防抖函数
function debounce(func, wait, immediate = true) {
  let timeout;
  return function () {
    if (timeout) clearTimeout(timeout);
    if (immediate) {
      var callNow = !timeout;
      timeout = setTimeout(() => {
        timeout = null;
      }, wait);
      if (callNow) func.apply(this, arguments);
    } else {
      timeout = setTimeout(function () {
        func.apply(context, args)
      }, wait)
    }
  }
}

export {
  newVue,
  addModel,
  updateModel,
  removeControl,
  addLink,
  updateLink,
  createGridLine,
  createGridLabel,
  createLineHeight0,
  updateLine,
  createPrimitive,
  renderSatBeam,
  updateBeam,
  showIsHideBeam,
  deleteBeam,
  debounce,
  tangent,
  createLine,
  updateSocketLine,
  addSmallModel
}
